package com.xq.filter;

import com.xq.utils.JwtBlacklistManager;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Value("${jwt.secret}")
    private String secretKey; // 从配置文件中加载密钥

    @Value("${jwt.expiration}")
    private long validityPeriod; // 从配置文件中加载过期时间

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtBlacklistManager blacklistManager; // 黑名单管理器

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // 如果是 Swagger 路径，直接放行
        String path = request.getRequestURI();
        if (path.startsWith("/swagger-ui") || path.startsWith("/v3/api-docs") || path.startsWith("/doc.html")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 从请求头中获取 Token
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 去掉 "Bearer " 前缀

            // 检查 Token 是否在黑名单中
            if (blacklistManager.isTokenBlacklisted(token)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("Token is blacklisted");
                return;
            }

            try {
                // 解析 Token
                Claims claims = Jwts.parser()
                        .setSigningKey("ccsens123!") // 使用相同的密钥解析
                        .parseClaimsJws(token)
                        .getBody();

                // 提取用户名
                String username = claims.getSubject();
                if (username != null) {
                   /* // 创建 Authentication 对象
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            username, null, new ArrayList<>());
                    SecurityContextHolder.getContext().setAuthentication(authentication);*/
                    //改用更加安全的写法，先验证用户存不存在
                    // 加载用户详细信息
                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);

                    // 创建 Authentication 对象
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            } catch (JwtException e) {
                // Token 解析失败或过期
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }
    }
